#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "Thread.hpp"
#include "INetAddr.hpp"
using namespace ThreadModule;

void Useage(const std::string& s)
{
    std::cout << s << ":\n\t" << " ip port\n";
}

int InitSocket(const std::string& ip, uint16_t port, struct sockaddr_in* server)
{
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socketfd < 0)
    {
        std::cout << "socket create fail" << std::endl;
        exit(1);
    }

    bzero(server, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(port);
    server->sin_addr.s_addr = inet_addr(ip.c_str());
    return socketfd;
}

void recvmessage(int socketfd, const std::string& name)
{
    while(true)
    {
        char buff[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        ssize_t n = recvfrom(socketfd, buff, sizeof(buff) - 1, 0, (sockaddr*)&peer, &len);
        if(n > 0)
        {
            buff[n] = '\0';
            INetAddr addr(peer);
            std::cout << name << "[" << addr.IP() << " : " << std::to_string(addr.Port()) << "] | " << buff << std::endl;
        }
    }
}

void sendmessage(int socketfd, struct sockaddr_in server, const std::string& name)
{
    std::string message;
    while(true)
    {
        std::cout << name << " | please enter#";
        std::getline(std::cin, message);
        ssize_t ret = sendto(socketfd, message.c_str(), message.size(), 0, (const sockaddr*)&server, sizeof server);
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    struct sockaddr_in server;
    int socketfd = InitSocket(ip, port, &server);
    
    // 2. 绑定套接字和网络信息
    // client 要不要 bind ? 一定要，client也需要IP 和 PORT 来标识自身唯一性
    //需不需要显示[类似server bind()]的bind ? 不需要，防止 client port 冲突，client 首次发送数据时，OS 会自动的随机的给client 进行bind 

    func_t r = std::bind(recvmessage, socketfd, std::placeholders::_1);
    func_t s = std::bind(sendmessage, socketfd, server, std::placeholders::_1);

    Thread recver(r, "recver");
    Thread sender(s, "sender");

    recver.Start();
    sender.Start();

    recver.Join();
    sender.Join();

    return 0;
}